﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using CommunitySystem.Web.IKey;
using CommunitySystemModel;
using CommunitySystem.BO.SystemManager;
using System.Collections.ObjectModel;
using CommunitySystem.Entity;
using CommunitySystem.BO.WordExport;


namespace CommunitySystem.Web.Service
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "SystemService" in code, svc and config file together.
    public class SystemService : ISystemService
    {
        #region 数据字典
        DataDictionaryBo _bo = DataDictionaryBo.GetInstance();
        public int SaveDataDictionary(DataDictionaryModel DataModel, ObservableCollection<DataDictionaryItemModel> DDIM)
        {
            return _bo.SaveDataDictionary(DataModel,DDIM);
        }

        public IList<DataDictionaryModel> GetDictionarys()
        {

            return _bo.GetDictionarys();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public IList<DataDictionaryItemModel> GetDataDictionaryItem(int parentId)
        {
            return _bo.GetDataDictionaryItem(parentId);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public IList<DataDictionaryModel> GetDataDictionary(int parentId)
        {
            return _bo.GetDataDictionary(parentId);
            //return null;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public int DeleteDataDictionary(int parentId)
        {
            return _bo.DeleteDataDictionary(parentId);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public int DeleteDataDictionaryItem(int ID)
        {
            return _bo.DeleteDataDictionaryItem(ID);
        }

        #endregion

        #region 用户管理
        UserInforModelDataContext db = new UserInforModelDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionDB"].ConnectionString);
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns></returns>
        public List<UserInfo> GetUserInfo()
        {
            return db.UserInfos.ToList();
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="UserInfoModel"></param>
        /// <returns></returns>
        public void InsertUser(UserInfo UserInfoModel)
        {
            db.UserInfos.InsertOnSubmit(UserInfoModel);
            db.SubmitChanges();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="UserInfoModel"></param>
        public void UpdateUser(UserInfo UserInfoModel)
        {
            var Model = db.UserInfos.SingleOrDefault<UserInfo>(s => s.UserID == UserInfoModel.UserID);
            if (Model != null)
            {
                //修改
                Model.LoginName=UserInfoModel.LoginName;
                Model.OrgCode = UserInfoModel.OrgCode;
                Model.PassWord = UserInfoModel.PassWord;
                Model.Phone = UserInfoModel.Phone;
                Model.RealName = UserInfoModel.RealName;
                Model.StreetCode = UserInfoModel.StreetCode;
                Model.Birthday = UserInfoModel.Birthday;
                Model.CreateDate = UserInfoModel.CreateDate;
                Model.Email = UserInfoModel.Email;
                Model.Gender = UserInfoModel.Gender;
                Model.RoleID = UserInfoModel.RoleID;

                db.SubmitChanges();
            }
            
    
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="UID"></param>
        public void DeleteUser(int UID)
        {
            var Model = db.UserInfos.SingleOrDefault<UserInfo>(s => s.UserID == UID);
            if (Model != null)
            {
                db.UserInfos.DeleteOnSubmit(Model);
                db.SubmitChanges();
            }
           
        }


        /// <summary>
        /// 用户登陆
        /// </summary>
        /// <param name="LoginName"></param>
        /// <param name="PassWord"></param>
        /// <returns></returns>
        private SystemBO sysbo = new SystemBO();
        public UserInfo Login(string LoginName, string PassWord, string DateString, string sig, bool NeedPasswordDog)
        {
            if (NeedPasswordDog)
            {
                IKey.UserAuthService client = new IKey.UserAuthService();
                client.Url = "http://31.0.2.70:3676";
                IKey.TtokenAuthReq Req = new IKey.TtokenAuthReq();

                Req.mi32Reserve = 1;
                Req.msAuthFromIP = "";

                //Req.msAuthName = "admin.Community";//认证名称  账户
                Req.msAuthName = LoginName;//用户
                Req.msAuthPasswd = sig;//Console.ReadLine();//"606690";//动态密码
                Req.mui8AuthType = 2;//认证类型
                ///1 串号
                ///2 用户名
                ///3 账户名

                Req.msChanllengeCode = "";
                Req.msHashResult = "";
                Req.msReserve1 = "";
                Req.msReserve2 = "";

                Req.ui32LocalSid = 1;
                Req.ui32ResId = 1;
                IKey.TtokenAuthRes Res = client.TokenAuth(Req);
                if (Res.i32Ret < 0)
                {
                    return new UserInfo()
                               {
                                   UserID = -1
                               };
                }
            }
            return sysbo.Login(LoginName, PassWord, DateString, sig, NeedPasswordDog);
            //var query = from t in db.UserInfos where t.LoginName == LoginName && t.PassWord == PassWord select t;
            

            //if (NeedPasswordDog)
            //{
            //    CAPICOM.SignedData date = new CAPICOM.SignedData();
            //    date.Content = DateString;
            //    date.Verify(sig, true, CAPICOM.CAPICOM_SIGNED_DATA_VERIFY_FLAG.CAPICOM_VERIFY_SIGNATURE_ONLY);
            //    string certbook = date.Signers[1].Certificate.Export();
            //    PrintControlOld.Common com = new PrintControlOld.Common();

            //    certbook = com.trimCert(ref certbook);
            //    string current = @"MIID1TCCAr2gAwIBAgIKFvHffwAAAAAAEDANBgkqhkiG9w0BAQUFADANMQswCQYDVQQDEwJicjAeFw0xMjExMjkwOTA4MTdaFw0xMzExMjkwOTE4MTdaMA8xDTALBgNVBAMTBHRlc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALL7iZeSsQlYdjlKlTafiW0p19c0dW1LNo5daBMKVwGMdSpDBfEIYHgFGBJNHRnbrrebbBABfFaTruNBfnndqXyV3o+D7k8Hx3mn6aQBbv5qkLNb1nS+IOAQgo5bQyoBpweitvMdzQu4OHN6b9FOYY3b0mMk83Ok8uH+AVflZtS5AgMBAAGjggG3MIIBszAOBgNVHQ8BAf8EBAMCBPAwRAYJKoZIhvcNAQkPBDcwNTAOBggqhkiG9w0DAgICAQAwDgYIKoZIhvcNAwQCAgEAMAcGBSsOAwIHMAoGCCqGSIb3DQMHMB0GA1UdDgQWBBQfbGrEpO1h7s1rCotApaBXtaMdUDATBgNVHSUEDDAKBggrBgEFBQcDAjAfBgNVHSMEGDAWgBQTGcouCVZvu19Z3KER3Ia8U66YSTBlBgNVHR8EXjBcMFqgWKBWhihodHRwOi8va3Nici0xMTQzZjZkNTUxL0NlcnRFbnJvbGwvYnIuY3JshipmaWxlOi8vXFxrc2JyLTExNDNmNmQ1NTFcQ2VydEVucm9sbFxici5jcmwwgZ4GCCsGAQUFBwEBBIGRMIGOMEQGCCsGAQUFBzAChjhodHRwOi8va3Nici0xMTQzZjZkNTUxL0NlcnRFbnJvbGwva3Nici0xMTQzZjZkNTUxX2JyLmNydDBGBggrBgEFBQcwAoY6ZmlsZTovL1xca3Nici0xMTQzZjZkNTUxXENlcnRFbnJvbGxca3Nici0xMTQzZjZkNTUxX2JyLmNydDANBgkqhkiG9w0BAQUFAAOCAQEAElHrFLe3lGjI3yGD6fBpCYSVxFCNZJOkwyKNdf9xgIQWktLNhKt1GNSnbVEqgOcbZlJG6GpMusR6XxajH199QvFSI9Pns0eCKvybNmSDx9c5+sSvk/vSbdaeykoeqO0aiE5IBrwABvwVVeZUyhY1mItep4RV6t1CzhgRqLENdTKje7DATuiCJKl+kWGjGDYq+gwq/EdHDWObfIu9V/nxFj2IctxvGlvJtIxReisISewGhuuV/xj9v1wNUZEyaIx9+9NhnSjEDTOUjKiB252y0sPiIh0qDbnCfLjR6DUu2XM+RJXGlTHuV4pfZs4FDixaa6vVlhDrveS/tTCZggsmOQ==";
            //    bool equals = certbook.Equals(current);
            //    if (!equals)
            //    {
            //        Dictionary<int, char[]> dict = new Dictionary<int, char[]>();
            //        for (int i = 0; i < current.Length && i < certbook.Length; i++)
            //        {
            //            if (certbook[i] != current[i])
            //                dict.Add(i, new char[2] { certbook[i], current[i] });
            //        }
            //    }
            //}
            //WordExportBO wordAction = new WordExportBO();
            //ObservableCollection<PersonnelInfoModelForWord> emps = new ObservableCollection<PersonnelInfoModelForWord>();
            //emps.Add(new PersonnelInfoModelForWord() { Name = "李子松", Gender = "男", Level = "中级", OriginalOrg = "徐汇区人保局", OriginalPosition = "干事", Political = "党员", Position = "科长" });
            //emps.Add(new PersonnelInfoModelForWord() { Name = "陈劼", Gender = "男", Level = "中级", OriginalOrg = "徐汇区人保局", OriginalPosition = "干事", Political = "党员", Position = "科长" });
            //emps.Add(new PersonnelInfoModelForWord() { Name = "童俊", Gender = "男", Level = "中级", OriginalOrg = "徐汇区人保局", OriginalPosition = "干事", Political = "党员", Position = "科长" });
            ////emps.Add(new PersonnelInfoModelForWord(){Name="YY", Gender="男", Level="中级", OriginalOrg="徐汇区人保局", OriginalPosition="干事", Political="党员", Position="科长"});
            //emps.Add(new PersonnelInfoModelForWord() { Name = "徐峰", Gender = "男", Level = "中级", OriginalOrg = "徐汇区人保局", OriginalPosition = "干事", Political = "党员", Position = "科长" });
            //wordAction.GerneratorXingZhenJieshaoXing("沪徐  2012  字第  68  号                                            沪徐  2012  字第  68  号", "", emps, "新录用", "组织部", "另转",
            //    "另转", new DateTime(2013, 7, 12), "参照公务员管理事业单位", "沈建华", DateTime.Now, "中共徐汇区委组织部", "公务员找路");

            //var ui  =query.ToList<UserInfo>().FirstOrDefault();
            //if (ui != null)
            //{
            //    string sql = "insert into CommunitySystemLoginStatistic (LoginName, LoginTime)  values ('" + ui.LoginName + "', '" + DateTime.Now.ToShortDateString() + "')";
            //    CommunitySystem.BO.AccessHelper.GetInstance().ExecuteNonQuery(sql);
            //}
            //return ui;

            #region ikey
            //UserAuthService service = new UserAuthService();
            ////service.Url = "http://192.168.88.35:3676";
            //service.Url = "http://192.168.1.107:3676";
            //TtokenAuthReq Req = new TtokenAuthReq();

            //Req.mi32Reserve = 1;
            //Req.msAuthFromIP = "";

            //Req.msAuthName = "admin.Community";//认证名称  账户
            ////Req.msAuthName = "admin";//用户
            //Req.msAuthPasswd = sig;//Console.ReadLine();//"606690";//动态密码
            //Req.mui8AuthType = 3;//认证类型

            /////1 串号
            /////2 用户名
            /////3 账户名

            //Req.msChanllengeCode = "";
            //Req.msHashResult = "";
            //Req.msReserve1 = "";
            //Req.msReserve2 = "";

            //Req.ui32LocalSid = 1;
            //Req.ui32ResId = 1;
            //TtokenAuthRes Res = service.TokenAuth(Req);
            ////Console.WriteLine(Res.i32Ret);
            ////Console.ReadLine();
            //if(Res.i32Ret < 0)
            //{
            //    return new UserInfo() {LoginName = Res.i32Ret + "", RealName = Res.szRet};
            //    //throw new Exception(Res.szRet);
            //}
            #endregion
            //var ui  =query.ToList<UserInfo>().FirstOrDefault();
            //if (ui != null)
            //{
            //    string sql = "insert into CommunitySystemLoginStatistic (LoginName, LoginTime)  values ('" + ui.LoginName + "', '" + DateTime.Now.ToShortDateString() + "')";
            //    CommunitySystem.BO.AccessHelper.GetInstance().ExecuteNonQuery(sql);
            //}
            //return ui;

        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="PassWord"></param>
        /// <param name="UID"></param>
        /// <returns></returns>
        public int UpdatePass(string PassWord,int UID)
        {
            var Model = db.UserInfos.SingleOrDefault<UserInfo>(s => s.UserID == UID);
            if (Model != null)
            {
                Model.PassWord = PassWord;
                db.SubmitChanges();
                return 1;
            }
            return 0;
        }

        /// <summary>
        /// 根据组织机构获取用户列表
        /// </summary>
        /// <returns></returns>
        public List<UserInfo> GetUserInfoByOrgNo(string OrgNo)
        {
            var Query = from t in db.UserInfos where t.OrgCode == OrgNo select t;
            return Query.ToList<UserInfo>();
        }
        #endregion

        #region 组织机构管理
        private readonly OrgInfoModelDataContext Orgdb = new OrgInfoModelDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionDB"].ConnectionString);

        /// <summary>
        /// 获取组织机构列表
        /// </summary>
        /// <returns></returns>
        public List<OrgInfo> GetOrgInfo()
        {
            return Orgdb.OrgInfos.ToList();
        }

        /// <summary>
        /// 新增组织机构
        /// </summary>
        /// <param name="UserInfoModel"></param>
        /// <returns></returns>
        public void InsertOrg(OrgInfo OrgInfoModel)
        {
            Orgdb.OrgInfos.InsertOnSubmit(OrgInfoModel);
            Orgdb.SubmitChanges();
        }

        /// <summary>
        /// 修改组织机构
        /// </summary>
        /// <param name="UserInfoModel"></param>
        public void UpdateOrg(OrgInfo OrgInfoModel)
        {
            var Model = Orgdb.OrgInfos.SingleOrDefault<OrgInfo>(s => s.Id == OrgInfoModel.Id);
            if (Model != null)
            {
                //修改
                Model.OrgNo = OrgInfoModel.OrgNo;
                Model.OrgName = OrgInfoModel.OrgName;
                Model.OrgJC = OrgInfoModel.OrgJC;
                Model.OrgManager = OrgInfoModel.OrgManager;
                Model.PID = OrgInfoModel.PID;
                Model.Sequence = OrgInfoModel.PID;
                

                Orgdb.SubmitChanges();
            }


        }

        /// <summary>
        /// 删除组织机构
        /// </summary>
        /// <param name="UID"></param>
        public string DeleteOrg(int UID)
        {
            var Model = Orgdb.OrgInfos.SingleOrDefault<OrgInfo>(s => s.Id == UID);
            if (Model != null)
            {
                //判断该组织机构下有没有人
                if (db.UserInfos.Where(p => p.OrgCode == Model.OrgNo).Count() > 0)
                {
                    return "组织机构有人员存在，无法删除!";
                }
                else
                {
                    //判断节点下是否存在字节点
                    if (Orgdb.OrgInfos.Where(p => p.PID == Model.Id).Count() > 0)
                        return "该组织机构下存在子节点，请删除子节点后再进行删除!";
                    else
                    {
                        Orgdb.OrgInfos.DeleteOnSubmit(Model);
                        Orgdb.SubmitChanges();
                        return "删除成功!";
                    }
                }

                
            }
            return "";
        }

        
        #endregion

        #region 角色管理

        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <returns></returns>
        public List<Role> GetRole()
        {
            return Orgdb.Roles.ToList();
        }
        /// <summary>
        /// 新增角色
        /// </summary>
        /// <param name="UserInfoModel"></param>
        /// <returns></returns>
        public void InsertRole(Role RoleModel)
        {
            Orgdb.Roles.InsertOnSubmit(RoleModel);
            Orgdb.SubmitChanges();
        }

        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="UserInfoModel"></param>
        public void UpdateRole(Role RoleModel)
        {
            var Model = Orgdb.Roles.SingleOrDefault<Role>(s => s.ID == RoleModel.ID);
            if (Model != null)
            {
                //修改
                Model.RoleName = RoleModel.RoleName;
                Model.DES = RoleModel.DES;
                Orgdb.SubmitChanges();
            }
        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="UserInfoModel"></param>
        public void DeleteRole(int RID)
        {
            var Model = Orgdb.Roles.SingleOrDefault<Role>(s => s.ID == RID);
            if (Model != null)
            {
                Orgdb.Roles.DeleteOnSubmit(Model);
                Orgdb.SubmitChanges();
            }

        }

        #endregion

        #region 权限管理
        /// <summary>
        /// 查询某个角色的权限
        /// </summary>
        /// <param name="RoleID"></param>
        /// <returns></returns>
        public ObservableCollection<RoleMenu> GetRoleMenu(int RoleID)
        {
            return bo.GetRoleMenu(RoleID);
        }
        RoleMenuBO bo = new RoleMenuBO();
        public bool UpdateRoleMenu(ObservableCollection<RoleMenu> rms)
        {
            return bo.UpdateRoleMenu(rms);
        }

        #endregion

        public ObservableCollection<int> GetCommunitySysteLoginTime(string loginname)
        {
            return new StatisticAnalysisBO().GetCommunitySysteLoginTime(loginname);
        }

        public  ObservableCollection<int> GetRegisterSysteLoginTime(string loginname)
        {
            return new StatisticAnalysisBO().GetRegisterSysteLoginTime(loginname);
        }
    }
}
